﻿using INTEX.DataBase;
using INTEX.DataBase.Tools;
using ReflectionStudio.Core.Events;
using ReflectionStudio.Core.Helpers;
using System;
using System.ComponentModel;
using System.Data;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using WPFExcelReport.Helpers;
namespace WPFExcelReport
{
    /// <summary>
    /// Interaction logic for EditEventWindow.xaml
    /// </summary>
    public partial class VWVKP
    {
        #region ==ABAUF===========
        public static readonly DependencyProperty ABAUFProperty = DependencyProperty.Register("ABAUF",
            typeof(string), typeof(VWVKP),
            new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnABAUFChanged));
        public string ABAUF
        {
            get
            {
                return (string)GetValue(ABAUFProperty);
            }
            set
            {
                SetValue(ABAUFProperty, value);
               

            }
        }
        private static void OnABAUFChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var src = sender as VWVKP;
            if (src != null)
            {
                src.ABAUF = (string)e.NewValue;
            }
        }
        #endregion
        #region ==BDMODE===========
        public static readonly DependencyProperty BDMODEProperty = DependencyProperty.Register("BDMODE",
            typeof(bool), typeof(VWVKP),
            new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnBDMODEChanged));
        public bool BDMODE
        {
            get
            {
                return (bool)GetValue(BDMODEProperty);
            }
            set
            {
                SetValue(BDMODEProperty, value);
                OnBDMODEChg();
            }
        }
        private static void OnBDMODEChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var src = sender as VWVKP;
            if (src != null)
            {
                src.BDMODE = (bool)e.NewValue;
            }
        }
        public virtual void OnBDMODEChg()
        { }
        #endregion
        public double LDT
        {
            get
            {
                return Convert.ToDouble(txtLDT.Text.ToString());
            }
        }

        public double LDX
        {
            get
            {
                return Convert.ToDouble(txtLDX.Text.ToString());
            }
        }
        public double LDR
        {
            get
            {
                return Convert.ToDouble(txtLDR.Text.ToString());
            }
        }
        public double RR01
        {
            get
            {
                return 1 + Convert.ToDouble(txtRR01.Text) / 100;
            }
        }
        bool IsLoaded = false;
        SETINTEXDB SetMaster
        {
            get
            {
                return vm.SetMaster;
            }
        }
        SETINTEXDB SetEnv
        {
            get
            {
                return vm.SetEnv;
            }
        }
        SETINTEXDB SetDetail
        {
            get
            {
                return vm.SetDetail;
            }
        }
        SETINTEXDB SetVKP
        {
            get
            {
                return vm.SetVKP;
            }
            set
            {
                vm.SetVKP = value;
            }
        }

        CollectionViewSource vwVKPOS
        {
            get
            {
                return (CollectionViewSource)TryFindResource("vwVKPOS");
            }
        }
        DataRow dwVKPOS
        {
            get
            {
                if (vwVKPOS.View == null)
                    return null;
                if ((DataRowView)vwVKPOS.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwVKPOS.View.CurrentItem).Row;
            }
        }
        CollectionViewSource vwABPOS
        {
            get
            {
                return (CollectionViewSource)TryFindResource("vwABPOS");
            }
        }
        DataRow dwABPOS
        {
            get
            {
                if (vwABPOS.View == null)
                    return null;
                if ((DataRowView)vwABPOS.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwABPOS.View.CurrentItem).Row;
            }
        }
        VYGRONAV95 vm;
        public string flag = "N";
        string PlanID = "YGR01";
        SolidColorBrush RedBrush = new SolidColorBrush();
        SolidColorBrush BlackBrush = new SolidColorBrush();
        BindingListCollectionView cvABP
        {
            get
            {
                return (BindingListCollectionView)CollectionViewSource.GetDefaultView(dlgABP.ItemsSource);
            }
        }
        BindingListCollectionView cvVKP
        {
            get
            {
                return (BindingListCollectionView)CollectionViewSource.GetDefaultView(dlgVKP.ItemsSource);
            }
        }
        private bool _IsInComositon;
        public bool IsInComositon
        {
            get
            {
                return _IsInComositon;
            }
            set
            {
                _IsInComositon = value;
                if (!value)
                {
                    this.cvVKP.CustomFilter = null;
                }
            }
        }
        public VWVKP()
        {

            InitializeComponent();
            this.Loaded += Windows_Loaded;
            if (app.User.Trim() == "ITXV")
            {
                KRS = "15";
                LFD = "000142";
                cmbTopsMakeUp.Text = "0.65";
            }
            RedBrush.Color = Colors.Red;
            BlackBrush.Color = Colors.Black;
        }

        void Windows_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            if (DesignerProperties.GetIsInDesignMode(this))
                return;
            if (IsLoaded)
                return;
            IsLoaded = true;
            vm = this.DataContext as VYGRONAV95;
            CheckFlow();
            if (vwVKPOS.View != null)
            {
                vwVKPOS.View.CurrentChanged += vwVKPOS_CurrentChanged;
            }
            string filter = "ABAWAKZ='G' AND ABAAUFTYP='V'";
            cvABP.CustomFilter = filter;
            //cvVKP.CustomFilter = "VKPRESERV=0";
        }

        bool IsResetPamameter = true;
        private void ResetUI()
        {

            if (SetEnv.Tables.Contains("GASTGA"))
            {
                SetEnv.GASTGA.Clear();
            }
            dlgXGS08.Visibility = Visibility.Collapsed;
            txtSQTYEND.Text = "0";
            txtSR01.Text = "0";
            txtXF01.Text = "0";
            txtXR01.Text = "0";
            txtSTOCK.Text = "0";
            txtSABACOLORREF.Text = "";
            txtTQTYEND.Text = "0";
            txtDDT.Text = "0";
            txtDST.Text = "0";
            txtLDT.Text = "0";
            txtTR01.Text = "0";
            cmbTwistFlow.SelectedIndex = -1;

            txtXQTYEND.Text = "0";

            txtXMNUM.Text = "0";
            txtXMDP.Text = "0";
            txtDDX.Text = "0";
            txtDSX.Text = "0";
            txtLDX.Text = "0";

            cmbSpinningFlow.SelectedIndex = -1;

            txtSR01.Text = "0";

            txtRQTYEND.Text = "0";
            txtDDR.Text = "0";
            txtDSR.Text = "0";
            txtLDR.Text = "0";


            cmbRolvingFlow.SelectedIndex = -1;

            txtTR01.Text = "0";
            cmbTopsMakeUp.SelectedIndex = -1;
            if (app.User.Trim() == "ITXV" || app.User.Trim() == "MAMN")
            {
                txtXMNUM.Text = "1";
                txtXMDP.Text = "10";
                cmbRolvingFlow.SelectedIndex = 0;
                cmbCombingType.SelectedIndex = 0;

            }
        }
        void vwVKPOS_CurrentChanged(object sender, EventArgs e)
        {

            try
            {
                using (new LongOperation(this, "查询数据"))
                {
                    if (app.User.Trim() == "ITXV")
                    {
                        cmbTopsMakeUp.Text = "0.25";
                    }

                    if (dwVKPOS == null)
                        return;
                    POS = dwVKPOS["VKPAUFPOS"].ToString();
                    BDMODE = false;
                    if (POS=="999")
                        BDMODE = true;
                    KEY = "";
                    KEY = "K" + dwVKPOS["VKPAUFKRS"].ToString() + dwVKPOS["VKPAUFLFD"].ToString() + dwVKPOS["VKPAUFPOS"].ToString(); 
                    ResetUI();
                    vm.dwVKP = dwVKPOS;
                    ResetPamameter();
                    //MainViewModel.LoadVKPOSData(dwVKPOS);
                    if (vm.LoadVKPOSData(dwVKPOS))
                    {
                        vm.IsPlan = false;
                        vm.IsPublish = false;
                        vm.IsDelete = true;
                        RefreshUI();
                        return;
                    }
                    vm.IsPlan = true;
                    vm.IsPublish = false;
                    vm.IsDelete = false;
                    flag = "N";
                    RefreshUI();
                    string VKPMENGE1 = dwVKPOS["VKPMENGE1"].ToString();
                    string VKPMEEHFKT = dwVKPOS["VKPMEEHFKT"].ToString();
                    //decimal VKPQTY = Math.Ceiling(Convert.ToDecimal(VKPMENGE1)
                    //    * Convert.ToDecimal(VKPMEEHFKT)
                    //    * Convert.ToDecimal(0.001)
                    //    * Convert.ToDecimal(0.001)
                    //    * Convert.ToDecimal(0.01));
                    decimal VKPQTY = Convert.ToDecimal(VKPMENGE1)
                        * Convert.ToDecimal(VKPMEEHFKT)
                        * Convert.ToDecimal(0.001)
                        * Convert.ToDecimal(0.001)
                        * Convert.ToDecimal(0.01);
                    txtSQTYEND.Text = Convert.ToDouble(VKPQTY).ToString();

                    IsResetPamameter = false;
                    CheckFlow();
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        public void Query()
        {
            try
            {
                ResetUI();
                vm.LoadData(null);
                SetMaster.AcceptChanges();
                if (vwVKPOS.View != null)
                {
                    vwVKPOS.View.MoveCurrentToFirst();
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        public void btnQuery_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ResetUI();
                SResult = new DataSet();
                dwData = SetMaster.VKPOS.NewRow();
                dwData["VKPMANDANT"] = "00";
                dwData["VKPAUFKRS"] = KRS;
                dwData["VKPAUFLFD"] = LFD;
                vm.LoadData(dwData);
                SetMaster.AcceptChanges();
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void TextBox_KeyDown(object sender, KeyEventArgs e)
        {
            TextBox tb = sender as TextBox;
            tb.Text = tb.Text.Trim();
            if (tb.Name.StartsWith("txtS"))
            {
                txtTQTYEND.Text = "-1";
                txtXQTYEND.Text = "-1";
                txtRQTYEND.Text = "-1";
            }

            if (tb.Name.StartsWith("txtT"))
            {
                txtXQTYEND.Text = "-1";
                txtRQTYEND.Text = "-1";
            }
            if (tb.Name.StartsWith("txtX"))
            {
                txtRQTYEND.Text = "-1";
            }
            if (tb.Name.StartsWith("txtDSR"))
            {
                //SetUpDating();
            }
            if (tb.Name.StartsWith("txtXR01"))
            {
                txtXF01.Text = "0";
            }
            if (tb.Name.StartsWith("txtXF01"))
            {
                txtXR01.Text = "0";
            }
        }

        private void btnResetP_Click(object sender, RoutedEventArgs e)
        {
            ResetPamameter();
        }
        private void ResetPamameter()
        {

            if (dwVKPOS == null)
            {
                return;
            }
            vm.PlanID = PlanID;
            if (SetEnv.Tables.Contains("PRULES"))
                SetEnv.Tables["PRULES"].Clear();
            string filter = "PLANID='" + PlanID + "'";
            DataTable tb = SetEnv.Tables["ICC_PRULES"].Select(filter).CopyToDataTable();
            tb.TableName = "PRULES";
            SetEnv.Merge(tb);
            double VKPQTY = 0;
            var qRules = from DataRow dwRule in SetEnv.Tables["PRULES"].AsEnumerable()
                         where dwRule["PLANID"].ToString().Trim() == PlanID
                         select dwRule;
            foreach (DataRow dwRule in qRules)
            {
                dwRule["DELDATE"] = vm.date;
                switch (dwRule["ARTSTAGE"].ToString().Trim())
                {
                    case "S":
                        string OVERSHORT = dwVKPOS["OVERSHORT"].ToString();
                        int idxstart = OVERSHORT.IndexOfAny(new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' });
                        int idxend = OVERSHORT.LastIndexOfAny(new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' });
                        if (idxend > 0)
                        {
                            OVERSHORT = OVERSHORT.Substring(idxend, 1);
                        }

                        if (OVERSHORT.Trim().Length == 0)
                        {
                            OVERSHORT = "0";
                        }
                        txtSR01.Text = OVERSHORT;
                        string VKPMENGE1 = dwVKPOS["VKPMENGE1"].ToString();
                        string VKPMEEHFKT = dwVKPOS["VKPMEEHFKT"].ToString();
                        VKPQTY = Math.Ceiling(Convert.ToDouble(VKPMENGE1)
                            * Convert.ToDouble(VKPMEEHFKT)
                            * Convert.ToDouble(0.001)
                            * Convert.ToDouble(0.001)
                            * Convert.ToDouble(0.01));
                        if (VKPQTY < 130)
                        {
                            txtXR01.Text = "0";
                            txtXF01.Text = "4";
                        }
                        else
                        {
                            txtXR01.Text = "4";
                            txtXF01.Text = "0";
                        }
                        string YARNTYPE = "P";
                        string ART = dwVKPOS["VKPART"].ToString();
                        int idx = ART.IndexOf(".");
                        string sj = ART.Substring(idx - 1, 1);
                        if (sj.ToUpper() == "J")
                        {
                            YARNTYPE = "J";
                        }

                        if (vm.GSGARNNR > 70)
                        {
                            YARNTYPE = "J";
                        }
                        if (YARNTYPE == "J")
                            cmbCombingType.SelectedIndex = 1;
                        else
                            cmbCombingType.SelectedIndex = 0;

                        foreach (ComboBoxItem cmb in cmbCombingType.Items)
                        {
                            if (((string)cmb.Tag) == YARNTYPE)
                            {

                            }
                        }

                        break;
                    case "T":
                        txtTR01.Text = dwRule["R01"].ToString();
                        txtLDT.Text = dwRule["LEADTIME"].ToString();
                        txtTQTYEND.Text = "-1";
                        txtSTOCK.Text = "0";
                        break;
                    case "X":
                        txtLDX.Text = dwRule["LEADTIME"].ToString();
                        txtXQTYEND.Text = "-1";
                        txtDDX.Text = "0";
                        txtDSX.Text = "0";
                        break;
                    case "R":
                        txtRR01.Text = dwRule["R01"].ToString();
                        txtLDR.Text = dwRule["LEADTIME"].ToString();
                        txtRQTYEND.Text = "-1";
                        txtRQTYMAT.Text = "-1"; ;
                        txtDDR.Text = "0";
                        txtDSR.Text = vm.date;
                        break;
                }

            }
        }

        private void txtVKPAUFLFD_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Enter)
            {
                btnQuery_Click(null, null);
            }
        }

        private bool SetUpDating()
        {
            #region===投料开始日期=======
            string DRS = txtDSR.Text;
            if (DRS.Trim().Length < 8)
            {
                MessageBox.Show("请设定投料开始日期");
                return false;
            }
            int leadtime = Convert.ToInt16(txtLDR.Text);
            txtDDR.Text = Helper.GetDateAddDays(DRS, leadtime);
            txtDSX.Text = txtDDR.Text;
            double 订单量 = 0;
            double 细纱量 = 0;
            细纱量 = (Convert.ToDouble(txtSQTYEND.Text) + Convert.ToDouble(txtXF01.Text) - Convert.ToDouble(txtSTOCK.Text))
                * (1 + Convert.ToDouble(txtSR01.Text) / 100 + Convert.ToDouble(txtXR01.Text) / 100);
            订单量 = Convert.ToDouble(txtSQTYEND.Text);
            double 台日产 = Convert.ToDouble(txtXMDP.Text);
            double 台数 = Convert.ToDouble(txtXMNUM.Text);
            if (台日产 == 0 || 台数 == 0)
            {
                MessageBox.Show("台日产*台数");
                return false;
            }
            double 细纱周期 = Math.Ceiling(细纱量 / (台数 * 台日产));
            txtLDX.Text = 细纱周期.ToString();
            string 细纱完成 = Helper.GetDateAddDays(txtDSX.Text, Convert.ToInt16(细纱周期));
            string 销售交期 = dwVKPOS["VKPLIEFTERM"].ToString();
            string 预计完成 = Helper.GetDateAddDays(细纱完成, 7);
            if (Convert.ToDecimal(预计完成) > Convert.ToDecimal(销售交期))
            {

                txtDDX.Foreground = RedBrush;
            }
            else
            {
                txtDDX.Foreground = BlackBrush;
            }
            txtDDX.Text = 细纱完成;
            txtDST.Text = txtDDX.Text;
            #endregion==========
            #region===投料系数=======
            string YARNTYP = (((ComboBoxItem)cmbCombingType.SelectedItem).Tag).ToString().Trim();

            //string filter = " WMIN<" + 订单量 + " AND "+订单量 +"<=WMAX" +  " AND TRIM(YARNTYP)='" + YARNTYP.Trim() + "'";
            //DataRow[] rows = SetEnv.Tables["ICC_AV95RULES"].Select(filter);
            foreach (DataRow row in SetEnv.Tables["ICC_AV95RULES"].Rows)
            {
                //订单量=100
                if (row["YARNTYP"].ToString().Trim() != YARNTYP)
                    continue;
                double WMIN = Convert.ToDouble(row["WMIN"].ToString());//80,130
                double WMAX = Convert.ToDouble(row["WMAX"].ToString());//130,200
                if (WMIN > 订单量)
                    continue;
                if (WMAX < 订单量)
                    continue;
                txtRR01.Text = (100 * (Convert.ToDouble(row["WASTAGE"].ToString()) - 1)).ToString();

            }
            txtRQTYMAT.Text = (Math.Ceiling(订单量 * RR01 * 1000) / 1000).ToString();
            #endregion==========
            return true;
        }
        private void btnPrePlan_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dwVKPOS == null)
                {
                    MessageBox.Show("请选择销售单行");
                    return;
                }
                if (!SetUpDating())
                    return;
                //MainViewModel.FilterData();
                #region======准备用户参与数据=======
                if (SetVKP == null)
                {
                    SetVKP = new INTEX.DataBase.SETINTEXDB();
                    SetVKP.Merge(SetDetail);
                }
                else
                {
                    SetDetail.Clear();
                    SetDetail.Merge(SetVKP);
                }
                if (SetEnv.Tables.Contains("GASTGA"))
                {
                    foreach (DataRow GS08 in SetEnv.Tables["GASTGA"].Rows)
                    {
                        var qGS08 = from DataRow dwGS08 in SetDetail.Tables["GASTGA"].AsEnumerable()
                                    where dwGS08["GAGART"].ToString() == GS08["GAGART"].ToString()
                                    && dwGS08["GAGVAR"].ToString() == GS08["GAGVAR"].ToString()
                                    && dwGS08["GAGFARBE"].ToString() == GS08["GAGFARBE"].ToString()
                                    && dwGS08["GAGPOS"].ToString() == GS08["GAGPOS"].ToString()
                                    select dwGS08;
                        foreach (DataRow dwGS08 in qGS08)
                        {
                            dwGS08["GAGANTEIL"] = GS08["GAGANTEIL"];
                        }
                    }
                }
                DataSet SResult = null;
                bool result = false;
                string flow = "";
                string filter = "RULEID>0 ";
                string sortby = "RULEID ASC";
                DataRow[] rows = SetEnv.Tables["PRULES"].Select(filter, sortby);
                string VKPLIEFTERM = dwVKPOS["VKPLIEFTERM"].ToString();

                string DateNow = vm.date;
                double XR01 = Convert.ToDouble(txtXR01.Text);//粗纱损耗
                double XF01 = Convert.ToDouble(txtXF01.Text);//粗纱损耗
                double SQTYEND = Convert.ToDouble(txtSQTYEND.Text);
                double RQTYEND = (SQTYEND + XF01) * (1 + XR01 / 100);
                txtRQTYEND.Text = (Math.Ceiling(RQTYEND * 100) / 100).ToString();
                txtXQTYEND.Text = txtRQTYEND.Text;
                txtTQTYEND.Text = txtRQTYEND.Text;
                foreach (DataRow dwRule in rows)
                {
                    switch (dwRule["ARTSTAGE"].ToString())
                    {
                        case "S":
                            dwRule["R01"] = txtSR01.Text; //交货范围
                            dwRule["ORDERNUM"] = Helper.Left(txtSABACOLORREF.Text.ToString().Trim().PadRight(10), 10);
                            dwRule["F02"] = txtSTOCK.Text;
                            dwRule["QTYEND"] = txtSQTYEND.Text;
                            dwRule["DELDATE"] = dwVKPOS["VKPLIEFTERM"];
                            dwRule["QTYMAT"] = txtRQTYEND.Text;
                            dwRule["F02DES"] = "PR";
                            if (BDMODE)
                            {
                                dwRule["F02DES"] = "BD";
                            }
                            break;
                        case "T":
                            if (vm.GSFACH > 1)
                            {
                                if (cmbTwistFlow.SelectedIndex == -1)
                                {
                                    throw new Exception("请选择并线流程");
                                }
                                dwRule["QTYEND"] = txtTQTYEND.Text;
                                dwRule["QTYMAT"] = txtTQTYEND.Text;
                                //dwRule["R01"] = txtTR01.Text;
                                dwRule["ORDERNUM"] = Helper.Left(txtSABACOLORREF.Text.ToString().Trim().PadRight(10), 10);
                                dwRule["DELDATE"] = txtDDT.Text;
                                dwRule["STARTDATE"] = txtDST.Text;
                                dwRule["LEADTIME"] = txtLDT.Text;
                                flow = (((ComboBoxItem)cmbTwistFlow.SelectedItem).Tag).ToString();
                                dwRule["UNDES"] = flow;
                            }
                            break;
                        case "X":
                            if (cmbSpinningFlow.SelectedIndex == -1)
                            {
                                throw new Exception("请选择细纱流程");
                            }
                            dwRule["QTYEND"] = txtXQTYEND.Text;
                            dwRule["QTYMAT"] = txtXQTYEND.Text;
                            dwRule["R01"] = txtXR01.Text;//粗纱损耗
                            dwRule["F01"] = txtXF01.Text;//粗纱加成，两者仅能有一个值
                            dwRule["F02DES"] = "   ";
                            if ((ComboBoxItem)cmbCombingType.SelectedItem != null)
                            {
                                dwRule["F02DES"] = (((ComboBoxItem)cmbCombingType.SelectedItem).Tag).ToString();
                            }
                            dwRule["UNITNUM"] = txtXMNUM.Text;
                            dwRule["UNITQTY"] = txtXMDP.Text;
                            dwRule["ORDERNUM"] = Helper.Left(txtSABACOLORREF.Text.ToString().Trim().PadRight(10), 10);
                            dwRule["DELDATE"] = txtDDX.Text;
                            dwRule["LEADTIME"] = txtLDX.Text;
                            dwRule["STARTDATE"] = txtDSX.Text;
                            flow = (((ComboBoxItem)cmbSpinningFlow.SelectedItem).Tag).ToString();
                            dwRule["UNDES"] = flow;
                            break;
                        case "R":
                            if (cmbRolvingFlow.SelectedIndex == -1)
                            {

                                throw new Exception("请选择粗纱流程");
                            }
                            if (cmbTopsMakeUp.SelectedIndex == -1)
                            {
                                throw new Exception("请选择粗纱定量");
                            }
                            dwRule["ORDERNUM"] = Helper.Left(txtSABACOLORREF.Text.ToString().Trim().PadRight(10), 10);
                            dwRule["QTYEND"] = txtRQTYEND.Text;
                            dwRule["R01"] = txtRR01.Text;//投料系数
                            dwRule["DELDATE"] = txtDDR.Text;
                            dwRule["LEADTIME"] = txtLDR.Text;
                            dwRule["STARTDATE"] = txtDSR.Text;
                            dwRule["QTYMAT"] = txtRQTYMAT.Text;
                            flow = (((ComboBoxItem)cmbRolvingFlow.SelectedItem).Tag).ToString();
                            dwRule["UNDES"] = flow;
                            string MU = (((ComboBoxItem)cmbTopsMakeUp.SelectedItem).Tag).ToString();
                            dwRule["R01DES"] = MU;
                            break;
                    }
                }
                #endregion
                SResult = vm.PrePlan(SetEnv, SetDetail, dwVKPOS);
                SetDetail.Clear();
                SetDetail.Merge(SResult);
                SetEnv.Tables["ICC_ABAX"].Clear();
                SetEnv.Merge(SetDetail.Tables["ICC_ABAX"]);
                RefreshUI();
                if (flag == "N")
                {
                    vm.IsPublish = true;
                }
                flag = "Y";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        VVKPOS VVKPOS = new VVKPOS();
        VGAAUF VGAAUF = new VGAAUF();

        private void btnCompensation_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dwVKPOS == null)
                {
                    MessageBox.Show("请选择销售单行");
                    return;
                }
                if (txtAddedQty.Text.Trim().ToString() == "" || txtAddedQty.Text.Trim().ToString() == "0")
                {
                    txtAddedQty.Visibility = Visibility.Visible; 
                    throw new Exception("请先输入补单数量");
                }
                //if (dwVKPOS["VKPRESERV"].ToString() == "0")
                //throw new Exception("尚未生产禁止计划");
                DataRow dwRow = INTEXDBC.Convert2VKPOS(dwVKPOS, app.company, true); ;

                dwRow["VKPAUFPOS"] = 999;
                dwRow["VKPEXAUFKRS"] = dwVKPOS["VKPAUFKRS"];
                dwRow["VKPEXAUFLFD"] = dwVKPOS["VKPAUFLFD"];
                dwRow["VKPEXAUFPOS"] = dwVKPOS["VKPAUFPOS"];
                dwRow["VKPMENGE1"] = Convert.ToDouble(txtAddedQty.Text.ToString()) * 100;
                dwRow["VKPRESERV"] = 0;
                dwRow["VKPRESERVT1"] = 0;
                dwRow["VKPRESERVT2"] = 0;
                dwRow["VKPRESERVT3"] = 0;
                dwRow["VKPRESERVT4"] = 0;

                VVKPOS.SaveVKPOS(dwRow, app.company);
                DataRow dwGA = null;
                var query = from DataRow row in SetDetail.Tables["GAAUF"].AsEnumerable()
                            where row["GAAUFKRS"].ToString() == dwVKPOS["VKPAUFKRS"].ToString()
                            && row["GAAUFLFD"].ToString() == dwVKPOS["VKPAUFLFD"].ToString()
                            && row["GAAUFPOS"].ToString() == dwVKPOS["VKPAUFPOS"].ToString()
                            select row;
                foreach (DataRow row in query)
                {
                    dwGA = row;
                }
                if (dwGA == null)
                    throw new Exception("纱线需求不存在");
                dwRow = VGAAUF.Convert2GAAUF(dwGA, app.company, true);
                dwRow["GAAUFPOS"] = 999;
                dwRow["GAKG1"] = Convert.ToDouble(txtAddedQty.Text.ToString()) * 100;
                VGAAUF.SaveGAAUF(dwRow, app.company);
                txtAddedQty.Text = "0";
                btnQuery_Click(null, null);
                cvVKP.CustomFilter = "VKPAUFPOS='999'";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void RefreshUI()
        {

            #region=======UpdateUI==========
            dlgXGS08.Visibility = Visibility.Collapsed;

            if (SetEnv.Tables.Contains("GASTGA"))
            {
                if (SetEnv.Tables["GASTGA"].Rows.Count > 1)
                {
                    dlgXGS08.Visibility = Visibility.Visible;
                }
            }
            txtXAUF.Text = "";
            txtTAUF.Text = "";
            txtRAUF.Text = "";
            DataRow dwABP = null;
            string filter = "";
            DataRow[] rows = null;
            filter = "ABAWAKZ='G'";
            rows = SetDetail.Tables["ICC_ABAX"].Select(filter);
            cmbTwistFlow.SelectedIndex = -1;
            cmbRolvingFlow.SelectedIndex = -1;
            cmbSpinningFlow.SelectedIndex = -1;
           /* cmbCombingType.SelectedIndex = -1;*/
            cmbTopsMakeUp.SelectedIndex = -1;
            string flow = "";
            ABAUF = "";
            foreach (DataRow dwMU in rows)
            {
                string ABAVKAUFTYP = dwMU["ABAVKAUFTYP"].ToString();
                string ABAVKAUFKRS = dwMU["ABAVKAUFKRS"].ToString();
                string ABAVKAUFLFD = dwMU["ABAVKAUFLFD"].ToString();
                string ABAVKAUFPOS = dwMU["ABAVKAUFPOS"].ToString();
                string ABAAUFTYP = dwMU["ABAAUFTYP"].ToString();
                string ABAAUFKRS = dwMU["ABAAUFKRS"].ToString();
                string ABAAUFLFD = dwMU["ABAAUFLFD"].ToString();
                string ABAAUFPOS = dwMU["ABAAUFPOS"].ToString();
                string ABPANRKR = "";
                //string UNDES = dwMU["UNDES"].ToString();
                /*参数存在前面的*
                 * 1.订单30留位到30
                 * 2.比如30是销售订单，20是细纱单，此时细纱单创建参数在这个单上
                 * 3.
                 */
                if (ABAVKAUFTYP == "K")
                {
                    txtSQTYEND.Text = dwMU["QTYEND"].ToString();
                    txtSR01.Text = dwMU["R01"].ToString();
                    txtSTOCK.Text = dwMU["F02"].ToString();
                    txtSABACOLORREF.Text = dwMU["ABACOLORREF"].ToString().Trim();
                }

                if (ABAVKAUFPOS.Trim() == "")
                    continue;
                if (ABAVKAUFPOS.Trim() == "000")
                    continue;
                filter = "ABPAUFKRS='" + ABAVKAUFKRS + "' AND ABPAUFLFD='" + ABAVKAUFLFD + "' AND ABPAUFPOS='" + ABAVKAUFPOS + "'";
                rows = SetDetail.Tables["ABPOS"].Select(filter);
                foreach (DataRow ABP in rows)
                {
                    ABPANRKR = ABP["ABPANRKR"].ToString();
                    flow = ABP["ABPANRKR"].ToString() + ABP["ABPALFDNR"].ToString();
                }
                if (ABPANRKR.Trim().Length == 0)
                    continue;
                switch (ABPANRKR)
                {
                    case "BX":
                        txtTAUF.Text = dwMU["ABAVKAUFKRS"].ToString() + "-" + Helper.GetSubRollNum(dwMU["ABAVKAUFLFD"].ToString());
                        txtTQTYEND.Text = dwMU["QTYEND"].ToString();
                        txtDDT.Text = dwMU["DELDATE"].ToString();
                        txtDST.Text = dwMU["STARTDATE"].ToString();
                        txtLDT.Text = dwMU["LEADTIME"].ToString();
                        flow = dwMU["UNDES"].ToString();
                        foreach (ComboBoxItem cmb in cmbTwistFlow.Items)
                        {
                            if (cmb.Tag.ToString().Trim() == flow.Trim())
                            {
                                cmbTwistFlow.Text = cmb.Content.ToString();
                            }
                        }
                        txtTR01.Text = dwMU["R01"].ToString();
                        break;
                    case "XS":
                        ABAUF = dwMU["ABAVKAUFKRS"].ToString() + dwMU["ABAVKAUFLFD"].ToString() + dwMU["ABAVKAUFPOS"].ToString();
                        txtXAUF.Text = dwMU["ABAVKAUFKRS"].ToString() + "-" + Helper.GetSubRollNum(dwMU["ABAVKAUFLFD"].ToString());
                        txtXQTYEND.Text = dwMU["QTYEND"].ToString();
                        txtXMNUM.Text = dwMU["UNITNUM"].ToString();
                        txtXMDP.Text = dwMU["UNITQTY"].ToString();
                        txtDDX.Text = dwMU["DELDATE"].ToString();
                        txtDSX.Text = dwMU["STARTDATE"].ToString();
                        txtLDX.Text = dwMU["LEADTIME"].ToString();
                        //flow = dwMU["UNDES"].ToString();
                        foreach (ComboBoxItem cmb in cmbSpinningFlow.Items)
                        {
                            if (cmb.Tag.ToString().Trim() == flow.Trim())
                                cmbSpinningFlow.Text = cmb.Content.ToString();
                        }
                        txtXR01.Text = dwMU["R01"].ToString();
                        txtXF01.Text = dwMU["F01"].ToString();
                        foreach (ComboBoxItem cmb in cmbCombingType.Items)
                        {
                            if (cmb.Tag.ToString().Trim() == dwMU["F02DES"].ToString().Trim())
                                cmbCombingType.Text = cmb.Content.ToString();
                        }
                        break;
                    case "HM":
                        txtRAUF.Text = dwMU["ABAVKAUFKRS"].ToString() + "-" + Helper.GetSubRollNum(dwMU["ABAVKAUFLFD"].ToString());
                        txtRQTYEND.Text = dwMU["QTYEND"].ToString();
                        txtDDR.Text = dwMU["DELDATE"].ToString();
                        txtDSR.Text = dwMU["STARTDATE"].ToString();
                        txtLDR.Text = dwMU["LEADTIME"].ToString();
                        //flow = dwMU["UNDES"].ToString();
                        foreach (ComboBoxItem cmb in cmbRolvingFlow.Items)
                        {
                            if (cmb.Tag.ToString().Trim() == flow.Trim())
                            {
                                cmbRolvingFlow.Text = cmb.Content.ToString();
                            }
                        }
                        txtRR01.Text = dwMU["R01"].ToString();
                        string MU = dwMU["R01DES"].ToString();
                        if (ABAAUFTYP == "V")
                        {
                            string filteraba = "ABAAUFKRS='" + ABAVKAUFKRS + "' AND ABAAUFLFD='" + ABAVKAUFLFD + "' AND ABAAUFPOS='" + ABAVKAUFPOS + "' AND ABAAUFMSL<>'  '";
                            DataRow[] rowsaba = SetDetail.Tables["ABAUFM"].Select(filteraba);
                            foreach (DataRow XP in rowsaba)
                            {
                                MU = XP["ABAAUFMSL"].ToString();
                            }
                        }
                        if (MU.Trim() == "")
                            continue;
                        foreach (ComboBoxItem cmb in cmbTopsMakeUp.Items)
                        {
                            if (cmb.Tag.ToString().Trim() == MU.Trim())
                                cmbTopsMakeUp.Text = cmb.Content.ToString();
                        }
                        break;
                }

            }
            #endregion
            if (vm.GSFACH > 1)
            {
                //ZoneTwist.Visibility = Visibility.Visible;

            }
            else
            {
                //ZoneTwist.Visibility = Visibility.Hidden;

            }
        }

        private void CheckFlow()
        {
            if (cmbSpinningFlow.Items.Count == 0)
            {
                foreach (DataRow row in SetEnv.Tables["APKOPF"].Rows)
                {
                    ComboBoxItem cmb = new ComboBoxItem();
                    cmb.Content = Helper.GetGB2312Value(row["APKSPEZIF"].ToString().Trim());
                    cmb.Tag = row["APKANRKRS"].ToString() + row["APKALFDNR"].ToString();
                    string APKANRKRS = row["APKANRKRS"].ToString();
                    switch (APKANRKRS)
                    {
                        case "BX":
                            cmbTwistFlow.Items.Add(cmb);
                            break;
                        case "XS":
                            cmbSpinningFlow.Items.Add(cmb);
                            break;
                        case "HM":
                            cmbRolvingFlow.Items.Add(cmb);
                            break;
                    }
                }
            }
            if (cmbTopsMakeUp.Items.Count == 0)
            {
                var query = from DataRow row in SetEnv.Tables["SDDAT"].AsEnumerable()
                            where row["SDSA"].ToString() == "0015"
                            select row;
                foreach (DataRow row in query)
                {
                    string SDKEY = row["SDKEY"].ToString().Trim();
                    if (!SDKEY.EndsWith("V"))
                        continue;
                    SDKEY = SDKEY.Substring(2, 2);
                    string MU = row["SDDATEN"].ToString().Substring(1, 20).Trim();
                    if (!MU.Contains("/m"))
                    {
                        continue;
                    }
                    ComboBoxItem cmb = new ComboBoxItem();
                    cmb.Content = Helper.Convert8859P1ToGB2312(MU).Replace("粗纱定量", "").Replace("g/m", "");
                    cmb.Tag = SDKEY;
                    cmbTopsMakeUp.Items.Add(cmb);
                }
            }
            if (dwVKPOS == null)
                return;
            if (vm.GSFACH > 1)
            {
                cmbTwistFlow.SelectedIndex = 0;
                cmbSpinningFlow.SelectedIndex = 1;
            }
            else
            {
                cmbSpinningFlow.SelectedIndex = 0;
            }
            if (cmbCombingType.SelectedIndex == 0)
            {
                cmbRolvingFlow.SelectedIndex = 3;
            }
            else
            {
                cmbRolvingFlow.SelectedIndex = 4;
            }
           
        }

        private void btnFlipPlanned_Click(object sender, RoutedEventArgs e)
        {
            return;
            Button btn = sender as Button;
            if (lblPlanned.Text.ToString().Trim() == "待排产")
            {
                cvVKP.CustomFilter = null;
                lblPlanned.Text = "所有";
            }
            if (lblPlanned.Text.ToString().Trim() == "所有")
            {
                cvVKP.CustomFilter = "VKPRESERV=0";
                lblPlanned.Text = "待排产";
            }
        }
    }
}
